package org.gl.logic;

import java.awt.Color;
import java.util.Date;
import java.util.Random;

import org.gl.obj.GLMap;

public class Rule01Logic extends GLMapLogic {

	private int step;
	private int diff;
	private boolean constr;
	
	/**
	 * 
	 * @param step step for r growth
	 * @param diff difference between avg and r value used in if condition
	 * @param constr while increasing step, should it be maxed to 255 or added mod 255
	 */
	public Rule01Logic(int step, int diff, boolean constr) {
		if(step < 0) throw new RuntimeException("Step < 0");
		if(diff < 0) throw new RuntimeException("Diff < 0");
		if(step >= 255) throw new RuntimeException("Step >= 255");
		if(diff >= 255) throw new RuntimeException("Diff >= 255");
		this.step = step;
		this.diff = diff;
		this.constr = constr;
	}
	
	@Override
	public void update(GLMap map) {
		GLMap temp = new GLMap(1, 1);
		temp.copy(map);
		for(int x = 1; x < map.getSizeX()-1; x++) {
			for(int y = 1; y < map.getSizeY()-1; y++) {
				//srednia arytmetyczna sasiadow
				int avg = (map.get(x-1, y-1).getRed()
						  +map.get(x-1, y).getRed()
						  +map.get(x-1, y+1).getRed()
						  +map.get(x, y-1).getRed()
						  +map.get(x, y+1).getRed()
						  +map.get(x+1, y-1).getRed()
						  +map.get(x+1, y).getRed()
						  +map.get(x+1, y+1).getRed())/8;
				int r = map.get(x, y).getRed();
				if(Math.abs(avg - r) > diff) {
					if(!constr) {
						r+=step;
						r%=255;
					} else {
						if(r < 255 - step) r+=step;
						else r = 255;
					}
				}
				else {
					r = (r + avg)%255;
				}
				temp.set(x, y, new Color(r, 0, 0));
			}
		}
		map.copy(temp);
	}
	
	@Override
	public void generateRandomSet(GLMap map) {
		Random r = new Random(new Date().getTime());
		for(int x = 0; x < map.getSizeX(); x++) {
			for(int y = 0; y < map.getSizeY(); y++) {
				map.set(x, y, new Color(r.nextInt(255), 0, 0));
			}
		}
	}
}